<template>
  <div>
    <el-row :gutter="12">
      <el-col :span="6">
        <el-input
          v-model="queryData.searchKey"
          placeholder="MQTT KEY或MQTT名称"
          size="small"
          clearable
          :maxlength="64"
          prefix-icon="el-icon-search"
        />
      </el-col>
      <el-col :span="6">
        <el-button type="primary" @click="loadData()">查询 </el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-col>

      <el-col :span="24" class="mt10">
        <DropdownButtons
          :buttons="[
            {
              icon: 'el-icon-circle-plus-outline',
              command: 'mqtt',
              title: '新建MQTT',
            },
            {
              icon: 'el-icon-upload2',
              command: 'importMqtt',
              title: '导入MQTT配置',
              upload: {
                accept: '.hm_mqtt',
                httpRequest: handleHttpRequest,
              },
            },
          ]"
          @command="handleCreate"
        />
      </el-col>
    </el-row>
    <el-table
      class="mt10 ds-table"
      :data="tableData"
      v-loading="loading"
      style="width: 100%"
      current-row-key="id"
      stripe
      border
    >
      <el-table-column type="expand">
        <template slot-scope="scope">
          <el-row :gutter="12">
            <el-col
              :span="8"
              v-for="item in scope.row.mqttSettings"
              :key="item.env"
            >
              <el-card
                v-if="getEnvActive(item.env)"
                class="mb10"
                shadow="never"
              >
                <div class="ds-table_env-title">
                  {{ getEnvName(item.env) }}
                </div>
                <el-form inline class="ds-table_env-info">
                  <el-form-item label="域名">
                    {{ item.host }}
                  </el-form-item>
                  <el-form-item label="端口">
                    {{ item.port }}
                  </el-form-item>
                  <el-form-item label="用户名">
                    {{ item.username }}
                  </el-form-item>
                  <el-form-item label="密码"> ****** </el-form-item>
                </el-form>
              </el-card>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column prop="key" label="MQTT KEY" />
      <el-table-column prop="name" label="MQTT名称" />
      <el-table-column prop="notes" label="描述" />
      <el-table-column prop="modifyDate" label="更新时间" width="180">
        <template slot-scope="scope">
          {{ scope.row.modifyDate | moment }}
        </template>
      </el-table-column>
      <el-table-column prop="actions" label="操作" width="250">
        <template slot-scope="scope">
          <span class="table-actionItem"
            ><el-button type="text" @click="handleEdit(scope.row)"
              >编辑</el-button
            ></span
          >
          <span class="table-actionItem" v-if="scope.row.type !== 'SYSTEM'">
            <el-popconfirm
              title="确认要删除该MQTT配置吗？"
              placement="top"
              @confirm="handleDelete(scope.row)"
            >
              <el-button class="link-danger" type="text" slot="reference"
                >删除</el-button
              >
            </el-popconfirm>
          </span>
          <span class="table-actionItem" v-if="scope.row.type !== 'SYSTEM'"
            ><el-button type="text" @click="handleExport(scope.row)"
              >导出</el-button
            ></span
          >
        </template>
      </el-table-column>
    </el-table>
    <MqttForm ref="MqttForm" />
  </div>
</template>
<script>
import {
  getHmmqttList,
  getHmmqttExport,
  postHmmqttImport,
  deleteHmmqtt,
} from "@/apis/paas/HmMqttLinkController.js"
import { getHmenvironmentList } from "@/apis/paas/HmEnvironmentController.js"
import { exportAppDataFromJson } from "@/utils/util"
import MqttForm from "./MqttForm.vue"
import DropdownButtons from "@/components/DropdownButtons/Index.vue"
export default {
  name: "MqttList",
  components: {
    DropdownButtons,
    MqttForm,
  },
  data() {
    return {
      loading: false,
      queryData: {},
      tableData: [],
      envConfigList: [], // 系统显示的环境
    }
  },
  created() {
    this.loadAllData()
  },
  methods: {
    async loadAllData() {
      this.envConfigList = await getHmenvironmentList({ hidden: 0 })
      this.loadData()
    },
    // 加载当前文件夹下的数据
    loadData() {
      this.loading = true
      const params = {
        ...this.queryData,
      }
      getHmmqttList(params)
        .then((res) => {
          this.tableData = res
        })
        .finally(() => {
          this.loading = false
        })
    },

    handleReset() {
      this.queryData = {}
      this.loadData()
    },
    getEnvActive(env) {
      const envItem = this.envConfigList.find((item) => item.key === env)
      return envItem && envItem.hidden === 0
    },
    getEnvName(env) {
      const envItem = this.envConfigList.find((item) => item.key === env)
      return envItem.name
    },
    handleCreate(command) {
      if (command === "mqtt") {
        this.$refs.MqttForm.open(undefined, () => {
          this.loadData()
          this.$message.success("操作成功")
        })
      }
    },

    handleEdit(record) {
      this.$refs.MqttForm.open(record, () => {
        this.loadData()
        this.$message.success("操作成功")
      })
    },

    handleDelete(record) {
      deleteHmmqtt([record.key]).then((res) => {
        this.loadData()
        this.$message.success("操作成功")
      })
    },
    /**
     * 导出
     * @param {*} record
     */
    async handleExport(record) {
      const res = await getHmmqttExport({
        id: record.id,
      })
      await exportAppDataFromJson({
        data: res,
        key: record.key,
        ext: "hm_mqtt",
      })
      setTimeout(() => {
        this.$message.success("导出成功")
      }, 1500)
    },

    /**
     * 导入
     * @param {*} file
     */
    async handleHttpRequest(file) {
      const formData = new FormData()
      formData.append("file", file.file)
      await postHmmqttImport(formData)
      this.$message.success("导入成功")
      this.loadData()
    },
  },
}
</script>
<style lang="scss" scoped>
.ds-table {
  &_env-title {
    line-height: 32px;
    font-weight: bold;
  }

  &_env-info .el-form-item {
    margin-right: 0;
    margin-bottom: 10px;
    width: 100%;
    display: flex;

    &:last-child {
      margin-bottom: 0;
    }

    ::v-deep label {
      width: 100px;
      color: #99a9bf;
      line-height: 24px;
      font-size: 12px;
      flex: none;
    }
    ::v-deep .el-form-item__content {
      line-height: 24px;
      font-size: 12px;
      flex: 1;
      word-break: break-all;
    }
  }
}
</style>
